package com.demo.shiro.controlloer;

import com.demo.shiro.model.UserInfo;
import com.demo.shiro.utils.MD5Utils;
import com.demo.shiro.utils.ResponseBo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;

/**
 * @author Jmy
 * @date 2019/7/26 19:00
 * @email jiaomingyu5778@gmail.com
 */
@Api(value = "登录Controller")
@Controller
public class LoginController {

    @ApiOperation(value = "用户登录", notes = "用户登录认证")
    @PostMapping("/login")
    public @ResponseBody ResponseBo login(@NotBlank(message = "{required}") String username,@NotBlank(message = "{required}") String password, boolean rememberMe) {
        // 把用户名当作盐，进行MD5计算
        password = MD5Utils.encrypt(username, password);
        // rememberMe 记住我，免登录设置
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        // 获取Subject对象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return ResponseBo.ok();
        } catch (UnknownAccountException e) {
            return ResponseBo.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return ResponseBo.error(e.getMessage());
        } catch (LockedAccountException e) {
            return ResponseBo.error(e.getMessage());
        } catch (AuthenticationException e) {
            return ResponseBo.error("认证失败！");
        }
    }

}
